import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.Vector;
import java.util.concurrent.LinkedBlockingQueue;

import javax.imageio.ImageIO;
import javax.swing.JFrame;



public class ReceiverThread extends Thread{
	final int Message = 1;
	final int Picture = 2;
	final int Changes = 3;
	final int NewTab = 4;
	final int TextFile = 5;
	final int ReciprocalConnection = 6;
	final int LeavingUser = 7;
	final int RequestAllDrawings = 8;
	final int ReceiveAllDrawings = 9;
	

	
	public ReceiverThread(LinkedBlockingQueue<DrawingChange> drawingQueue, LinkedBlockingQueue<String> chatQueue, Socket SocketConnection, PaintGUI AboveGUI){

		System.out.println("new receiver thread started ");
		try{
			if(SocketConnection == null) {
				return;
			}
			System.out.println("Host and port are   "  + SocketConnection.getLocalAddress().getHostName() + SocketConnection.getPort());
			DataInputStream dis = new DataInputStream(SocketConnection.getInputStream());
	        int TypeOfTransfer = dis.readInt();
	        System.out.println(TypeOfTransfer);

	        if(TypeOfTransfer == Message) {
	                String textFromOthers = dis.readUTF();
	                chatQueue.add(textFromOthers + "\n");
	        }
	        else if(TypeOfTransfer == Picture) {
	            int PixelsInPictureOrChangesInArray = dis.readInt();
	            int PictureWidth = dis.readInt();
	            BufferedImage img = new BufferedImage(PictureWidth, PixelsInPictureOrChangesInArray/PictureWidth, BufferedImage.TYPE_INT_RGB);
	            
	            int[] RGBs = new int [PixelsInPictureOrChangesInArray];
	            for(int p = 0; p < PixelsInPictureOrChangesInArray; p++) {
	                    RGBs[p] = dis.readInt();
	            }
	            for(int p = 0; p < PixelsInPictureOrChangesInArray; p++) {
	            	img.setRGB(p%PictureWidth, p/PictureWidth, RGBs[p]);
	            }
	            
	            try {
	                File outputfile = new File("saved.png");
	                ImageIO.write(img, "png", outputfile);
	            } catch (IOException e) {
	            	System.out.println("new image was not saved");
	            }
	            
	            JFrame frame2 = new JFrame();
	            JPanelForPicture panel = new JPanelForPicture(img);
	            frame2.setSize(700, 700);
	            frame2.add(panel);
	            frame2.setVisible(true);
	            panel.repaint();
	            frame2.repaint();
	        }
	        else if (TypeOfTransfer == Changes) {
	                String TabToChange = dis.readUTF();
	                int ChangesInArray = dis.readInt();
	                Vector<PointDrawn> Changes = new Vector<PointDrawn>();
	                for(int c = 0; c < ChangesInArray; c++) {
	                        int x1 = dis.readInt();
	                        int y1 = dis.readInt();
	                        int radius = dis.readInt();
	                        int clr = dis.readInt();
	                        int FakeBool = dis.readInt();
	                        PointDrawn CurChange = new PointDrawn(x1, y1, radius, new Color(clr), FakeBool == 1);
	                        Changes.add(CurChange);
	                }
	                DrawingChange newChange = new DrawingChange(Changes, TabToChange);
	                drawingQueue.add(newChange);
	        }
	        else if (TypeOfTransfer == NewTab) {
	        	String Title = dis.readUTF();
	        	String UniqueTabName = dis.readUTF();
	        	System.out.println("should add another tab");
	        	AboveGUI.addAnotherPaintingTabForAll(Title, UniqueTabName);
	        }
	        else if(TypeOfTransfer == TextFile) {
	        	Vector<String> TextFileAsVector = new Vector<String>();
	        	int NumberOfLines = dis.readInt();
	        	int i = 0;
	        	while(NumberOfLines < i) {
	        		String CurLine = dis.readUTF();
	        		TextFileAsVector.add(CurLine);
	        		System.out.println(CurLine);
	        	}
	        	AboveGUI.SaveTextFileReceived(TextFileAsVector);
	        }
	        else if(TypeOfTransfer == ReciprocalConnection) {
	        	System.out.println("Reciprocal came in to this side");
	        	String ForeignHost = dis.readUTF();
	        	AboveGUI.possiblyAddHost(ForeignHost);
	        }
	        else if(TypeOfTransfer == LeavingUser) {
	        	String leavingUserHostName = dis.readUTF();
	        	AboveGUI.deleteUser(leavingUserHostName);
	        }
	        else if(TypeOfTransfer == RequestAllDrawings) {
	        	AboveGUI.sendAllDrawings(SocketConnection.getInetAddress().getHostName());
	        }
	        else if(TypeOfTransfer == ReceiveAllDrawings) {
                String uniqueTabName = dis.readUTF();
                String tabTitle = dis.readUTF();
                if(!AboveGUI.tabPresent(uniqueTabName)) AboveGUI.addAnotherPaintingTabForAll(tabTitle, uniqueTabName);
                int ChangesInArray = dis.readInt();
                Vector<PointDrawn> Changes = new Vector<PointDrawn>();
                for(int c = 0; c < ChangesInArray; c++) {
                        int x1 = dis.readInt();
                        int y1 = dis.readInt();
                        int radius = dis.readInt();
                        int clr = dis.readInt();
                        int FakeBool = dis.readInt();
                        PointDrawn CurChange = new PointDrawn(x1, y1, radius, new Color(clr), FakeBool == 1);
                        Changes.add(CurChange);
                }
                DrawingChange newChange = new DrawingChange(Changes, uniqueTabName);
                drawingQueue.add(newChange);
	        }
	        else {
	                System.out.println("In else of Receiver Listen() method");
	        }
	        SocketConnection.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
		
	}
}